﻿using Microsoft.Owin;
using Microsoft.Owin.FileSystems;
using Microsoft.Owin.Security.ActiveDirectory;
using Microsoft.Owin.StaticFiles;
using Owin;
using SqueezeMe;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.IdentityModel.Tokens;

namespace Sustainalytics.ComprehensiveESGResearch.UI.Service
{
    public class Startup
    {
        private readonly string ClientAppPath = ConfigurationManager.AppSettings["clientAppPath"];
        private readonly string AdalTenant = ConfigurationManager.AppSettings["adal:Tenant"];
        private readonly string AdalClientId = ConfigurationManager.AppSettings["adal:ClientId"];

        public void Configuration(IAppBuilder app)
        {
            app.UseAngularHtml5Mode();

            var fileServerOptions = new FileServerOptions
            {
                EnableDefaultFiles = true,
                EnableDirectoryBrowsing = false,
                RequestPath = PathString.Empty,
                FileSystem = new PhysicalFileSystem(ClientAppPath),
            };
            app.UseFileServer(fileServerOptions);

            app.UseCompression();

            var adalOptions = new WindowsAzureActiveDirectoryBearerAuthenticationOptions
            {
                Tenant = AdalTenant,
                TokenValidationParameters = new TokenValidationParameters { ValidAudience = AdalClientId }
            };
            app.UseWindowsAzureActiveDirectoryBearerAuthentication(adalOptions);
        }
    }

    public static class OwinExtensions
    {
        public static IAppBuilder UseAngularHtml5Mode(this IAppBuilder app)
        {
            app.Use(async (context, next) =>
            {
                await next.Invoke();

                if (context.Response.StatusCode == 404)
                {
                    context.Request.Path = new PathString("/");
                    await next.Invoke();
                }
            });

            return app;
        }
    }
}
